package other.edan.intlpass.certificate;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.CertificateRegistration__c;
import com.rkhd.platform.sdk.data.model.User;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.AsyncTaskException;
import com.rkhd.platform.sdk.exception.EmailException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.EmailBody;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.EmailService;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.edan.intlpass.entity.Email;
import other.edan.intlpass.utils.HCXObjectService;
import other.edan.intlpass.utils.SendEmailUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 发送过期提醒邮件
 * @Author 黎炎松
 * 2025-02-25 16:29
 */
public class SendExpireEmail implements ScheduleJob, FutureTask {
   
    private static final XoqlService xoqlService = XoqlService.instance();

    private static final Logger LOGGER = LoggerFactory.getLogger();

    private static String LOGGER_MSG = "发送市场活动附件客户的邮件 ==> ";

    /**
     * 触发定时任务
     * @param scheduleJobParam
     */
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        try {
            FutureTaskService.instance().addFutureTask(getClass(), "");
        } catch (AsyncTaskException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 执行异步
     * @param s
     * @throws ScriptBusinessException
     */
    @Override
    public void execute(String s) {
        sendNoticeEmail();
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        //new SendExpireEmail().sendNoticeEmail();

        CertificateRegistration__c certificateRegistration__c = new CertificateRegistration__c();
        certificateRegistration__c.setId(3623013134686530L);
        certificateRegistration__c.setIsSendEmail__c(1);
        HCXObjectService.update(certificateRegistration__c);
    }

    /**
     * 发送通知邮件
     */
    private void sendNoticeEmail() {
        try {
            LOGGER.info(LOGGER_MSG + "处理开始");

            // 查询过期的注册证书  有效期小于等于180天
            long timestamp = System.currentTimeMillis();
            long daysTamp = 1000 * 60 * 60 * 24; // 天
            String sql = String.format("select id,name,nation__c,(deadlineDate__c - %s) / %s as expireDays  from certificateRegistration__c " +
                    " where (isSendEmail__c is null or isSendEmail__c = 2) and deadlineDate__c is not null and (deadlineDate__c - %s) / %s <= 180", timestamp, daysTamp, timestamp, daysTamp);
            List<JSONObject> certificateList = xoqlService.query(sql).getRecords();
            if (certificateList.size() <= 0) {
                LOGGER.info(LOGGER_MSG + "没有过期的注册证书，无需处理");
                return;
            }

            // 根据国家档案进行分组
            Map<String, List<JSONObject>> nationMap = certificateList.stream().collect(Collectors.groupingBy(e -> e.getString("nation__c")));

            // 获取国家档案找到对应的业务员邮箱
            String nationIds = nationMap.keySet().stream().collect(Collectors.joining(","));
            sql = String.format("select id,salesma__c,nationalArchives__c from ServicePartitionTable__c where nationalArchives__c in (%s)", nationIds);
            List<JSONObject> servicePartitionList = xoqlService.query(sql).getRecords();

            // 根据名称查询用户
            String names = servicePartitionList.stream().map(v -> "'" + v.getString("salesma__c") + "'").distinct().collect(Collectors.joining(","));
            sql = String.format("select id,name,personalEmail from user where name in (%s)", names);
            Map<String, String> userListMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getString("name"), e1 -> e1.getString("personalEmail")));

            // 根据国际档案匹配用户邮箱
            Map<String, String> userEmailMap = new HashMap<>();
            servicePartitionList.forEach(v -> {
                String salesma = v.getString("salesma__c");
                if (userListMap.containsKey(salesma)) {
                    userEmailMap.put(v.getString("nationalArchives__c"), userListMap.get(salesma));
                }
            });

            // 获取发送内容
            for (String nation : nationMap.keySet()) {
                if (!userEmailMap.containsKey(nation)) {
                    continue;
                }
                List<JSONObject> zsList = nationMap.get(nation);
                String certificateNames = zsList.stream().map(v -> v.getString("name")).collect(Collectors.joining(","));

                Email email = new Email();
                email.setSubject("注册证书过期提示"); // 主题
                email.setContent(String.format("  %s 编号的证书即将过期，请及时处理", certificateNames)); // 内容
                email.setReceiverList(Arrays.asList(userEmailMap.get(nation))); // 收件人列表
                LOGGER.info(LOGGER_MSG + "email = "  +email);
                SendEmailUtils.sendEmail(email);
            }

            // 更新注册证书 发送邮件标识
            List<CertificateRegistration__c> crmUpList = certificateList.stream().map(v -> {
                CertificateRegistration__c upCertificateRegistration = new CertificateRegistration__c();
                upCertificateRegistration.setId(v.getLong("id"));
                upCertificateRegistration.setIsSendEmail__c(1);
                return upCertificateRegistration;
            }).collect(Collectors.toList());
            HCXObjectService.updateBatch(crmUpList);

            LOGGER.info(LOGGER_MSG + "处理完成");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info(LOGGER_MSG + "处理异常: " + e.getMessage());
        }
    }




}
